﻿/*
 *  创建者：    
 *      zlk
 *  创建时间：
 *      2011-7-20
 *  文件说明：
 *      文件上传下载辅助类
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;
using Sunimage.Spjg.Common.Exceptions;

namespace Sunimage.Spjg.Web.Helper
{
    public class FileUpDownHelper
    {
        public static void Download(string name, string file)
        {
            HttpContext.Current.Response.AddHeader("Content-Type", MimeTypesHelper.GetMimeType(Path.GetExtension(file)));
            HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" +
                HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8).Replace("+", "%20"));
            HttpContext.Current.Response.BinaryWrite(System.IO.File.ReadAllBytes(file));
            HttpContext.Current.Response.End(); // TODO:加还是不加？是不是加了以后报错？
        }

        public static string Upload(FileUpload fu, string fileTitle)
        {
            return Upload(fu, System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName(), fileTitle);
        }

        public static string Upload(FileUpload fu, string directory, string fileName, string fileTitle)
        {
            if (!fu.HasFile || fu.FileName.Length == 0)
            {
                throw new BusinessObjectLogicException("请选择文件： " + fileTitle + "！");
            }

            string filePath = null;
            try
            {
                if (directory.EndsWith("\\"))
                    filePath = directory + fileName;
                else
                    filePath = directory + "\\" + fileName;


                if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);

                fu.SaveAs(filePath);
            }
            catch
            {
                throw new BusinessObjectLogicException(fileTitle + " 文件上传失败！");
            }

            return filePath;
        }
    }
}
